package nb.diskfilesystem;

import javafx.animation.ScaleTransition;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.effect.DropShadow;
import javafx.scene.Cursor;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.layout.VBox;
import javafx.geometry.Pos;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.paint.CycleMethod;
import javafx.scene.control.Tooltip;
import javafx.util.Duration;
import javafx.scene.layout.HBox;

public class DiskVisualization {

    // 定义配色方案
    private static final String PRIMARY_COLOR = "#1a73e8";    // 主色调
    private static final String SECONDARY_COLOR = "#4285f4";  // 次要色调
    private static final String BACKGROUND_COLOR = "#ffffff"; // 背景色
    private static final String BORDER_COLOR = "#e0e0e0";    // 边框色

    // 绘制磁盘块视图
    public static void drawBlockView(BorderPane blockView) {
        // 创建最外层容器
        VBox mainContainer = new VBox(10);
        mainContainer.setAlignment(Pos.CENTER);
        mainContainer.setPadding(new Insets(15));
        mainContainer.setStyle("""
            -fx-background-color: %s;
            -fx-background-radius: 15;
            -fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.1), 10, 0, 0, 0);
        """.formatted(BACKGROUND_COLOR));

        // 创建标题标签
        Label titleLabel = new Label("磁盘块分布图");
        titleLabel.setStyle("""
            -fx-font-size: 16px;
            -fx-font-weight: bold;
            -fx-text-fill: #333333;
        """);
        HBox titleBox = new HBox(titleLabel);
        titleBox.setAlignment(Pos.CENTER);
        titleBox.setPadding(new Insets(0, 0, 5, 0));

        GridPane gridPane = new GridPane();
        gridPane.setHgap(3);
        gridPane.setVgap(3);
        gridPane.setAlignment(Pos.CENTER);

        // 遍历所有128个块
        for (int i = 0; i < 128; i++) {
            Rectangle block = new Rectangle(30, 30);
            block.setArcWidth(8);
            block.setArcHeight(8);

            int status = FATManage.getFATStatus(i);
            if (status != 0) {
                block.setFill(Color.web(SECONDARY_COLOR));
                addGlowEffect(block);
            } else {
                block.setFill(Color.web(BACKGROUND_COLOR));
            }

            block.setStroke(Color.web(BORDER_COLOR));
            block.setStrokeWidth(1);

            // 添加悬停效果
            setupHoverEffect(block, status);
            // 添加工具提示
            setupTooltip(block, i, status);

            gridPane.add(block, i % 16, i / 16);
        }

        // 添加图例
        HBox legend = new HBox(20);
        legend.setAlignment(Pos.CENTER);
        legend.setPadding(new Insets(5, 0, 0, 0));

        // 已使用图例
        HBox usedLegend = new HBox(5);
        Rectangle usedBlock = new Rectangle(15, 15);
        usedBlock.setFill(Color.web(SECONDARY_COLOR));
        usedBlock.setArcWidth(4);
        usedBlock.setArcHeight(4);
        Label usedLabel = new Label("已使用");
        usedLabel.setStyle("-fx-text-fill: #666666;");
        usedLegend.getChildren().addAll(usedBlock, usedLabel);

        // 空闲图例
        HBox freeLegend = new HBox(5);
        Rectangle freeBlock = new Rectangle(15, 15);
        freeBlock.setFill(Color.WHITE);
        freeBlock.setStroke(Color.web(BORDER_COLOR));
        freeBlock.setArcWidth(4);
        freeBlock.setArcHeight(4);
        Label freeLabel = new Label("空闲");
        freeLabel.setStyle("-fx-text-fill: #666666;");
        freeLegend.getChildren().addAll(freeBlock, freeLabel);

        legend.getChildren().addAll(usedLegend, freeLegend);

        mainContainer.getChildren().addAll(titleBox, gridPane, legend);
        blockView.setCenter(mainContainer);
        BorderPane.setMargin(mainContainer, new Insets(10, 10, 10, 0));  // 上、右、下、左
    }

    // 绘制圆形使用率视图
    public static void drawCircleView(BorderPane circleView) {
        VBox container = new VBox(10);
        container.setAlignment(Pos.CENTER);
        container.setPadding(new Insets(15));
        container.setStyle("""
            -fx-background-color: %s;
            -fx-background-radius: 15;
            -fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.1), 10, 0, 0, 0);
        """.formatted(BACKGROUND_COLOR));

        // 创建标题标签
        Label titleLabel = new Label("磁盘使用率");
        titleLabel.setStyle("""
            -fx-font-size: 16px;
            -fx-font-weight: bold;
            -fx-text-fill: #333333;
        """);

        // 修改这里：使用绝对定位的Pane来容纳标题和圆环
        Pane contentPane = new Pane();
        contentPane.setPrefSize(200, 250); // 调整整体容器大小

        HBox titleBox = new HBox(titleLabel);
        titleBox.setAlignment(Pos.CENTER);
        // 设置标题的位置
        titleBox.setLayoutX(160); // 调整水平位置
        titleBox.setLayoutY(-50); // 调整垂直位置

        double radius = 95;
        double centerX = radius;
        double centerY = radius;

        Pane pane = new Pane();
        pane.setPrefSize(radius * 2, radius * 2);
        pane.setMaxSize(radius * 2, radius * 2);
        pane.setMinSize(radius * 2, radius * 2);

        // 创建外层装饰圆环
        Circle decorativeCircle = new Circle(centerX, centerY, radius);
        decorativeCircle.setFill(Color.web("#f8f9fa"));
        decorativeCircle.setStroke(Color.web(BORDER_COLOR));
        decorativeCircle.setStrokeWidth(1);

        double percentage = calculateUsedPercentage();

        // 创建进度圆环
        Arc progressArc = new Arc(
                centerX, centerY,
                radius - 15, radius - 15,
                90,
                -(percentage * 360)
        );
        progressArc.setType(ArcType.OPEN);
        progressArc.setFill(Color.TRANSPARENT);
        progressArc.setStroke(createGradient());
        progressArc.setStrokeWidth(12);
        progressArc.setStrokeLineCap(StrokeLineCap.ROUND);

        // 创建中心圆
        Circle centerCircle = new Circle(centerX, centerY, radius - 35);
        centerCircle.setFill(Color.web(BACKGROUND_COLOR));
        centerCircle.setStroke(Color.web(BORDER_COLOR));
        centerCircle.setStrokeWidth(1);

        VBox labelBox = createUsageLabels(percentage);
        // 直接设置固定位置
        labelBox.setLayoutX(centerX);
        labelBox.setLayoutY(centerY);

        pane.getChildren().addAll(decorativeCircle, progressArc, centerCircle, labelBox);

        // 设置圆环容器的位置
        pane.setLayoutX(105); // 调整水平位置
        pane.setLayoutY(20); // 调整垂直位置，使其往上移

        // 将标题和圆环都添加到contentPane中
        contentPane.getChildren().addAll(titleBox, pane);
        container.getChildren().add(contentPane);

        circleView.setCenter(container);
        BorderPane.setMargin(container, new Insets(10, 0, 0, 0));
    }

    // 辅助方法
    private static void addGlowEffect(Rectangle block) {
        DropShadow glow = new DropShadow();
        glow.setColor(Color.web(SECONDARY_COLOR, 0.3));
        glow.setRadius(10);
        block.setEffect(glow);
    }

    private static void setupHoverEffect(Rectangle block, int status) {
        block.setOnMouseEntered(e -> {
            ScaleTransition scale = new ScaleTransition(Duration.millis(150), block);
            scale.setToX(1.1);
            scale.setToY(1.1);
            scale.play();
            block.setCursor(Cursor.HAND);
        });

        block.setOnMouseExited(e -> {
            ScaleTransition scale = new ScaleTransition(Duration.millis(150), block);
            scale.setToX(1.0);
            scale.setToY(1.0);
            scale.play();
        });
    }

    private static void setupTooltip(Rectangle block, int index, int status) {
        Tooltip tooltip = new Tooltip(
                String.format("块号: %d\n状态: %s",
                        index,
                        status != 0 ? "已使用" : "空闲")
        );
        tooltip.setStyle("-fx-font-size: 12px;");
        Tooltip.install(block, tooltip);
    }

    private static LinearGradient createGradient() {
        Stop[] stops = new Stop[]{
                new Stop(0, Color.web(PRIMARY_COLOR)),
                new Stop(1, Color.web(SECONDARY_COLOR))
        };
        return new LinearGradient(0, 0, 1, 0, true, CycleMethod.NO_CYCLE, stops);
    }

    private static VBox createUsageLabels(double percentage) {
        VBox labelBox = new VBox(5);
        labelBox.setAlignment(Pos.CENTER);
        // 预设宽度和高度以避免重新计算导致的跳动
        labelBox.setPrefWidth(100);
        labelBox.setPrefHeight(60);

        Label percentageLabel = new Label(String.format("%.1f%%", percentage * 100));
        percentageLabel.setStyle("""
            -fx-font-size: 24px;
            -fx-font-weight: bold;
            -fx-text-fill: #333333;
        """);

        Label usageLabel = new Label("已使用空间");
        usageLabel.setStyle("""
            -fx-font-size: 13px;
            -fx-text-fill: #666666;
        """);

        labelBox.getChildren().addAll(percentageLabel, usageLabel);
        // 确保标签在VBox中居中
        labelBox.setTranslateX(-50);  // 预设偏移量，使其居中
        labelBox.setTranslateY(-30);

        return labelBox;
    }

    // 计算使用率
    private static double calculateUsedPercentage() {
        int usedBlocks = 0;
        int totalBlocks = 128;

        for (int i = 0; i < totalBlocks; i++) {
            if (FATManage.getFATStatus(i) != 0) {
                usedBlocks++;
            }
        }

        return (double) usedBlocks / totalBlocks;
    }

    // 更新两个视图
    public static void updateViews(BorderPane blockView, BorderPane circleView) {
        drawBlockView(blockView);
        drawCircleView(circleView);
    }
}